<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="query">
            <el-button slot="append" @click="serch" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table
          :data="tableData"
          stripe
          border
          style="width: 100%">
        <el-table-column
            fixed
            prop="userId"
            label="id"
            width="50"
        >
        </el-table-column>
        <el-table-column
            prop="loginName"
            label="姓名"
            width="80"
        >
        </el-table-column>
        <el-table-column
            prop="userName"
            label="账号"
            width="100"
        >
        </el-table-column>
        <el-table-column
            prop="email"
            label="邮箱"
            width="180">
        </el-table-column>
        <el-table-column
            prop="phonenumber"
            label="手机号"
            width="130">
        </el-table-column>
        <el-table-column
            prop="sex"
            label="性别"
            width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.sex==1">男</el-tag>
            <el-tag type="danger" v-else>女</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="avatar"
            label="头像"
            width="120">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" width="80" height="50px" />
          </template>
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            width="80">
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                active-color="#13ce66"
                @change="changeStatus(scope.row.userId,scope.row.status)"
                inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
            prop="createBy"
            label="创建人"
            width="80">
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间"
            width="180">
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="160">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="EditUser(scope.row.userId)"  size="medium" circle></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="Delete(scope.row)"  size="medium" circle></el-button>
            <el-button type="success" icon="el-icon-s-tools" size="medium" @click="FenRoles(scope.row)"  circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

      <!--修改弹框的 表单 -->
      <el-dialog
          title="修改用户信息"
          :visible.sync="EditDialogVisible"
          width="50%"
          @close="closeEditUser"
          >
        <el-form :model="EditFormData" status-icon :rules="EditFormRules" ref="EditRuleForm" label-width="80px" class="demo-ruleForm">
          <el-form-item label="姓名" prop="loginName">
            <el-input type="text" v-model="EditFormData.loginName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="userName">
            <el-input type="text" readonly v-model="EditFormData.userName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input type="text"  v-model="EditFormData.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phonenumber">
            <el-input type="text" v-model="EditFormData.phonenumber" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <template>
              <el-radio v-model="EditFormData.sex" label="1">男</el-radio>
              <el-radio v-model="EditFormData.sex" label="0">女</el-radio>
            </template>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="EditDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmEditUser">确 定</el-button>
        </span>
      </el-dialog>


      <!--添加弹框的 表单 -->
      <el-dialog
          title="添加用户信息"
          :visible.sync="AddDialogVisible"
          width="50%"
          @close="closeAddUser"
      >
        <el-form :model="AddFormData" status-icon :rules="AddFormRules" ref="AddRuleForm" label-width="80px" class="demo-ruleForm">
          <el-form-item label="姓名" prop="loginName">
            <el-input type="text" v-model="AddFormData.loginName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="userName">
            <el-input type="text"  v-model="AddFormData.userName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input type="text"  v-model="AddFormData.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phonenumber">
            <el-input type="text" v-model="AddFormData.phonenumber" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <template>
              <el-radio v-model="AddFormData.sex" label="1">男</el-radio>
              <el-radio v-model="AddFormData.sex" label="0">女</el-radio>
            </template>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="AddDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmAddUser">确 定</el-button>
        </span>
      </el-dialog>


      <!--分配角色的弹框 -->
      <el-dialog
          :title="title"
          :visible.sync="FenRoleDialogVisible"
          width="50%"
      >
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
          <el-checkbox v-for="role in roles" :label="role.roleId" :key="role.roleId">{{role.roleName}}</el-checkbox>
        </el-checkbox-group>

        <span slot="footer" class="dialog-footer">
          <el-button @click="FenRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmFenRole">确 定</el-button>
        </span>
      </el-dialog>


    </el-card>
  </div>
</template>

<script>
export default {
  name: "user",
  data(){
    return{
      //查询条件
      query:"",
      //当前页码
      currentPage: 1,
      //每页显示记录
      pageSize:5,
      //总条数
      total:0,
      //当前的记录数据
      tableData: [],


      //是否打开修改弹框 true 打开 false 关闭
      EditDialogVisible: false,
      //修改弹框表单的数据
      EditFormData:{},
      //修改弹框 表单的 规则
      EditFormRules:{
        loginName:[
          {required:true,message:"用户名不能为空",trigger:"blur"}
        ],
        userName:[
          {required:true,message:"账号不能为空",trigger:"blur"},
          {min:5,max:14,message: "账号的长度必须为5~14",trigger: "blur"}
        ],
        email:[
          {required:true,message:"邮箱不能为空",trigger:"blur"},
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur'] }
        ],
        phonenumber:[
          {required:true,message:"手机号不能为空",trigger:"blur"},
          { min: 11, max: 11, message: "请输入11位手机号码", trigger: "blur" },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },

      //是否打开 添加弹框
      AddDialogVisible: false,
      //添加表单的数据
      AddFormData:{},
      //添加表单的规则
      AddFormRules:{
        loginName:[
          {required:true,message:"用户名不能为空",trigger:"blur"}
        ],
        userName:[
          {required:true,message:"账号不能为空",trigger:"blur"},
          {min:5,max:14,message: "账号的长度必须为5~14",trigger: "blur"}
        ],
        email:[
          {required:true,message:"邮箱不能为空",trigger:"blur"},
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phonenumber:[
          {required:true,message:"手机号不能为空",trigger:"blur"},
          { min: 11, max: 11, message: "请输入11位手机号码", trigger: "blur" },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },

      //是否打开分配角色弹框
      FenRoleDialogVisible: false,
      //为那个用户分配 角色
      title:"分配角色信息",
      checkAll: false,
      checkedRoles: [],
      roles: [],
      isIndeterminate: true,
      userId:0,

    }
  },
  //页面加载自动执行
  created() {
    this.initUserTable(this.currentPage,this.pageSize);
  },
  methods: {
    //修改每页几条的方法
    handleSizeChange(val) {
      this.pageSize=val;
      this.initUserTable(this.currentPage,this.pageSize);
    },
    //修改页数的方法
    handleCurrentChange(val) {
      this.currentPage=val;
      this.initUserTable(this.currentPage,this.pageSize);
    },
    //模糊查询按钮的方法
    serch(){
      this.initUserTable(this.currentPage,this.pageSize);
    },
    //初始化表格的方法
    initUserTable(currentPage,pageSize){
      var that = this;
        this.$http.post(`/sys/user/findUserByPage/${currentPage}/${pageSize}?query=${this.query}`).then(function (res){
          if (res.data.code==200){
            that.tableData=res.data.data.records;
            that.total=res.data.data.total;
          }else{
            that.$message.error("用户信息加载失败");
          }
        })
    },
    //修改弹框回显的方法
    EditUser(userId){
      this.EditDialogVisible = true;
      //console.log(userId);
      var that = this;
      this.$http.get(`/sys/user/getUserById/${userId}`).then(function (res){
        that.EditFormData=res.data.data;
      })
    },
    //提交修改弹框的方法
    confirmEditUser(){
      var that = this;
      this.$refs['EditRuleForm'].validate((valid) => {
        if (valid) {
          that.$http.put("/sys/user/updateUser",this.EditFormData).then(function (res){
            if (res.data.code == 200){
              that.$message.success("修改成功");
              that.EditDialogVisible=false;
              that.initUserTable(that.currentPage,that.pageSize);
            }else{
              that.$message.error("修改失败");
            }
          })
        }
      })
    },
    //修改 状态的方法
    changeStatus(userId,status){
      var that = this;
        this.$http.put(`/sys/user/updateStatusByUserId/${userId}/${status}`).then(function (res){
          if (res.data.code == 200){
              that.$message.success(res.data.msg);
              that.initUserTable(that.currentPage,that.pageSize);
          }else{
              that.$message.error(res.data.msg);
          }
        })
    },
    //添加按钮的弹框的方法
    addUser(){
      this.AddDialogVisible=true;
    },
    //提交添加表单的方法
    confirmAddUser(){
      //console.log(this.AddFormData);
      var that = this;
      this.$refs['AddRuleForm'].validate((valid) => {
        if (valid) {
          this.$http.post("/sys/user/addUser", this.AddFormData).then(function (res) {
            if (res.data.code == 200) {
              //console.log(res);
              that.$message.success(res.data.msg);
              that.AddDialogVisible = false;
              /*that.AddFormData = {};*/
              that.initUserTable(that.currentPage, that.pageSize);
            } else {
              that.$message.error(res.data.msg);
            }
          })
        }
      })
    },
    //打开分配弹框 并回显数据的 方法
    FenRoles(row){
      var that = this;
      this.userId = row.userId;
      this.title = "为"+row.userName+"分配角色"
      this.$http.get("/sys/role/getAllRoles/"+row.userId).then(function (res){
        if (res.data.code ==200){
          that.roles=res.data.data.roles; //得到所有的角色
          that.checkedRoles=res.data.data.userRoles; // 得到该用户的角色
          that.FenRoleDialogVisible = true;
        }

      })
    },
    //提交分配权限的弹出框
    confirmFenRole(){
      //console.log(this.checkedRoles)
      var that =this;
      this.$http.post("/sys/role/confirmFenRole",{userId:this.userId,roleIds:this.checkedRoles}).then(function (res){
          if (res.data.code==200){
              that.$message.success(res.data.msg);
              that.FenRoleDialogVisible = false;
          }else {
            that.$message.error("修改用户角色失败")
          }
      })
    },
    handleCheckAllChange(val) {
      if (val){
        this.roles.forEach(item => {
          this.checkedRoles.push(item.roleId);
        })
      }else{
        this.checkedRoles = [];
      }
      this.isIndeterminate = false;
    },
    handleCheckedRolesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roles.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
    },
    //删除用户的确认弹框
    Delete(row){
      var that=this;
      this.$confirm('是否删除用户:'+row.loginName+'?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.$http.get(`/sys/user/deleteUserById/${row.userId}`).then(function(res){
          if (res.data.code == 200){
            if (that.total%that.pageSize==1){
              that.currentPage--;
            }else {
              that.currentPage = that.currentPage;
            }
            that.$message.success(res.data.msg);
            that.initUserTable(that.currentPage,that.pageSize);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //修改弹框关闭时触发的方法
    closeEditUser(){
      this.$refs.EditRuleForm.resetFields();
    },
    //添加弹框关闭时触发的方法
    closeAddUser(){
      this.$refs.AddRuleForm.resetFields();
    }


  }

}
</script>

<style scoped>

</style>